// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let db = cloud.database()
  const _ = db.command
  //增加销售量
  if (event.type == 1) {
    for (let i = 0; i < event.order.length; i++) {
      db.collection('product_details').doc(event.order[i].id).update({
          data: {
            sale: _.inc(event.order[i].count)
          }
        })
        .then(e => {
          console.log('更新成功', e)
        })
        .catch(err => {
          console.log("更新失败", err)
        })
    }
  } else if (event.type == 2) {
    for (let i = 0; i < event.order.length; i++) {
      db.collection('product_details').doc(event.order[i].id).update({
          data: {
            sale: _.inc(event.order[i].count)
          }
        })
        .then(res => {
          db.collection('cart').doc(event.order[i]._id).remove()
            .then(e => {
              console.log('删除购物车商品成功', res)
            })
            .catch(er => {
              console.log("删除购物车商品失败", er)
            })
        })
        .catch(err => {
          console.log("更新失败", err)
        })
    }
  } else {
    for (let i = 0; i < event.order.length; i++) {
      db.collection('menu').doc(event.order[i].id).update({
          data: {
            m_sale: _.inc(event.order[i].count)
          }
        })
        .then(e => {
          console.log('更新成功', e)
        })
        .catch(err => {
          console.log("更新失败", err)
        })
    }
  }

}